package com.ctg.payroll2.action.sysadmin;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.ctg.payroll2.bean.po.SysFunction;
import com.ctg.payroll2.bean.po.SysUser;
import com.ctg.payroll2.service.sysadmin.MenuService;
import com.ctg.payroll2.util.Constants;
import com.ctg.payroll2.util.MenuRecursion;
import com.ctg.platform.core.security.SpringSecurityManager;
import com.ctg.platform.core.security.entity.Resource;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unchecked")
public class MenuAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4320244822145214315L;
	// JSON 返回 拼装的 jsonString
	private String jsonString = "";

	public String getJsonString() {

		return jsonString;
	}

	public void setJsonString(String jsonString) {

		this.jsonString = jsonString;

	}

	private MenuService menuService;

	
	private SpringSecurityManager springSecurityManager;
	
	
	public void setSpringSecurityManager(SpringSecurityManager springSecurityManager) {
		this.springSecurityManager = springSecurityManager;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	// 得到申请书类型，绑定到类型树
	public String bindAsTree() {
		try {
			SysUser user = (SysUser)ServletActionContext.getRequest().getSession().getAttribute(Constants.CURRENT_USER);
			if(user==null)
				return Constants.RELOGIN;
			List <Resource> listResource =springSecurityManager.getPrivilegesByLoginName(user.getLoginName(), user);
			StringBuffer sb = new StringBuffer();
			sb.append("'").append(Constants.MENU_ROOT_ID).append("',");
			for(int i = 0 ;i< listResource.size();i++ ){
				if(i==listResource.size()-1){
					sb.append("'"+listResource.get(i).getId()+"'");
				}else{
					sb.append("'"+listResource.get(i).getId()+"',");
				}
			}
			
			List<SysFunction> list = menuService.getFuctions(sb.toString());
			if (list != null && !list.isEmpty()) {
				//MenuRecursion 拼装menuTree类 
				jsonString = MenuRecursion.getString(list);
				System.out.println(jsonString);
				//add by luli begin
				jsonString = jsonString.substring(32+Constants.MENU_ROOT_ID.length(), jsonString.length()-2);
				//add by luli end
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

}
